package tech.xs.common.framework.util;


import tech.xs.common.framework.domain.entity.BaseEntity;

import java.util.*;

public class BaseEntityUtil {

    /**
     * 获取实体类ID集合
     *
     * @param list 源数据
     * @param <T>  数据类型
     * @return id列表
     */
    public static <T extends BaseEntity> List<Long> toIdList(Collection<T> list) {
        List<Long> idList = new ArrayList<>(list.size());
        for (BaseEntity item : list) {
            idList.add(item.getId());
        }
        return idList;
    }

    /**
     * 获取实体类ID集合
     *
     * @param list 源数据
     * @param <T>  数据类型
     * @return id列表
     */
    public static <T extends BaseEntity> Set<Long> toIdSet(Collection<T> list) {
        Set<Long> idSet = new HashSet<>(list.size());
        for (BaseEntity item : list) {
            idSet.add(item.getId());
        }
        return idSet;
    }

    /**
     * 转换成map
     *
     * @param list 数据列表
     * @param <T>  数据类型
     * @return id和数据的映射
     */
    public static <T extends BaseEntity> Map<Long, T> toIdMap(Collection<T> list) {
        Map<Long, T> idMap = new HashMap<>(list.size());
        for (T item : list) {
            idMap.put(item.getId(), item);
        }
        return idMap;
    }

    /**
     * 根据id去重
     *
     * @param list 源数据
     * @param <T>  数据类型
     * @return 去重后的数据
     */
    public static <T extends BaseEntity> Set<T> duplicateRemovalByIdToSet(Collection<T> list) {
        return duplicateRemovalByIdToCollection(list, new HashSet<>());
    }

    public static <T extends BaseEntity> List<T> duplicateRemovalByIdToList(Collection<T> list) {
        return duplicateRemovalByIdToCollection(list, new ArrayList<>());
    }

    public static <T extends BaseEntity, R extends Collection<T>> R duplicateRemovalByIdToCollection(Collection<T> list, R res) {
        for (T item : list) {
            boolean exist = false;
            for (T r : res) {
                if (r.getId().equals(item.getId())) {
                    exist = true;
                    break;
                }
            }
            if (!exist) {
                res.add(item);
            }
        }
        return res;
    }

}
